from openpyxl import load_workbook, Workbook
from pathlib import Path


# 封装读取excel表格中内容的函数
def read_excel(path, sheet_name='Sheet1'):
    # 1、打开工作簿workbook
    wb = load_workbook(path)
    # 2、切换工作表worksheet
    ws = wb[sheet_name]
    # 3、确定单元格

    data_list = []
    for row in ws.iter_rows(values_only=True):
        data_list.append(row)
    return data_list


def to_dict(data: list) -> list[dict]:
    keys = data[0]
    values = data[1:]
    data_dict = []
    for value in values:
        data = dict(zip(keys, value))
        data_dict.append(data)
    return data_dict


# 封装向excel表格中写入内容的函数
def save_excel(path, sheet_name, data_list):
    if Path(path).exists():
        raise ValueError("不可以覆盖已有的xlsx文件")

    wb = Workbook()  # 新工作簿
    if sheet_name in wb:
        ws = wb[sheet_name]
    else:
        ws = wb.create_sheet(sheet_name)
    for row in data_list:
        ws.append(row)
    wb.save(path)


if __name__ == '__main__':  # 如果excel_tools.py文件被其他文件调用，下面这两行代码不会被执行
    data = read_excel("../files/data.xlsx", "Sheet1")
    # print(data)
    save_excel("../files/new_data.xlsx", "Sheet3", data)
